{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 1. 用Pytorch构建两个模型，分别是回归预测和分类预测。要求定义成类的形式。",
   "id": "5a6d218f70016135"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "#回归预测模型\n",
    "class RegressionModel(nn.Module):\n",
    "    def __init__(self,input_size,output_size=1):\n",
    "        super(RegressionModel, self).__init__()\n",
    "        self.fc1 = nn.Linear(input_size,128)\n",
    "        self.fc2 = nn.Linear(128,64)\n",
    "        self.fc3 = nn.Linear(64,output_size)\n",
    "\n",
    "    def forward(self,x):\n",
    "        x = torch.relu(self.fc1(x))\n",
    "        x = torch.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x\n",
    "\n",
    "#分类预测模型\n",
    "class ClassificationModel(nn.Module):\n",
    "    def __init__(self,input_size,num_classes):\n",
    "        super(ClassificationModel, self).__init__()\n",
    "        self.fc1 = nn.Linear(input_size,128)\n",
    "        self.fc2 = nn.Linear(128,64)\n",
    "        self.fc3 = nn.Linear(64,num_classes)\n",
    "\n",
    "    def forward(self,x):\n",
    "        x = torch.relu(self.fc1(x))\n",
    "        x = torch.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x"
   ],
   "id": "c4f80ddf90c2ac36"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 2. 定义一个train函数，在函数中完成对模型的训练，\n",
    "```\n",
    "def train(model, train_data_loader, epochs):\n",
    "```\n",
    "返回训练好的模型"
   ],
   "id": "332ad388bd79ef1a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-11-02T11:15:02.011537Z",
     "start_time": "2025-11-02T11:15:01.990847Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def train(model,train_data_loader,epochs):\n",
    "    criterion = nn.MSELoss()        # 用于回归问题\n",
    "    # criterion = nn.CrossEntropyLoss()  # 用于分类问题\n",
    "    optimizer = torch.optim.Adam(model.parameters(),lr=0.001)\n",
    "    model.train()\n",
    "\n",
    "    for epoch in range(epochs):\n",
    "        for data,targets in train_data_loader:\n",
    "            optimizer.zero_grad()\n",
    "            outputs = model(data)\n",
    "            loss = criterion(outputs,targets)\n",
    "            loss.backward()\n",
    "            optimizer.step()\n",
    "    return model"
   ],
   "id": "fc73224719c5a507",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3. 定义一个eval函数，在函数中完成对模型的评估，\n",
    "```\n",
    "def eval(model, test_data_loader, eval_metrics):\n",
    "```\n",
    "注意eval_metrics是一个函数，根据不同类型的任务传入不同函数对模型进行评估：\n",
    "- 回归 MSE\n",
    "- 分类 准确率"
   ],
   "id": "900bce31e0405739"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-11-02T11:27:04.124159Z",
     "start_time": "2025-11-02T11:27:04.092267Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def eval(model, test_data_loader, eval_metrics):\n",
    "    model.eval()\n",
    "    total_score = 0.0\n",
    "    batch_count = 0\n",
    "\n",
    "    with torch.no_grad():\n",
    "        for inputs, labels in test_data_loader:\n",
    "            predictions = model(inputs)\n",
    "            score = eval_metrics(predictions, labels)\n",
    "            total_score += score\n",
    "            batch_count += 1\n",
    "\n",
    "    return total_score / batch_count\n",
    "\n",
    "def mse_metric(predictions, labels):\n",
    "    return torch.mean((predictions - labels) ** 2).item()\n",
    "\n",
    "def accuracy_metric(predictions, labels):\n",
    "    _, predicted_labels = torch.max(predictions, 1)\n",
    "\n",
    "    correct = (predicted_labels == labels).float().mean()\n",
    "\n",
    "\n",
    "    return correct.item()"
   ],
   "id": "df7b0a476bc09324",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "2a26642be85a601f"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
